package com.digicom.admin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Spring Security配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义用户认证方式
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 此处简化处理，实际项目应该使用实现了UserDetailsService的自定义服务
        auth.inMemoryAuthentication()
            .withUser("admin")
            .password(bCryptPasswordEncoder().encode("123456"))
            .roles("ADMIN");
    }

    /**
     * 安全配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // CSRF禁用，因为不使用session
            .csrf().disable()
            // 基于token，所以不需要session
            .sessionManagement().disable()
            // 允许跨域
            .cors()
            .and()
            // 对请求授权
            .authorizeRequests()
            // 对于登录接口，允许匿名访问
            .antMatchers("/login", "/captcha").anonymous()
            // 静态资源，可匿名访问
            .antMatchers("/css/**", "/js/**", "/images/**", "/favicon.ico").permitAll()
            // 除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated()
            .and()
            // 定义登录页面
            .formLogin()
            .loginPage("/login")
            .permitAll();
    }

    /**
     * 获取权限判断服务
     */
    @Bean("ss")
    public PermissionService permissionService() {
        return new PermissionService();
    }
} 